package theList;

import com.sun.deploy.net.proxy.RemoveCommentReader;

/**
 * @author wangchenghao
 * @date 2021/6/26
 **/
public class test2 {
    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (n < 1) {
            return null;
        }
        ListNode p1 = head;
        ListNode p2 = head;
        int index=0;
        //p1先前进k-1步
        for (int i = 0; i < n && p1 != null; i++) {
            p1 = p1.next;
            index++;
        }
        if (p1 == null) {
            if (index==n){
                head=head.next;
                return head;
            }else {
                System.out.println("k不合法");
                return null;
            }
        }
        while (p1.next != null) {
            p1 = p1.next;
            p2 = p2.next;
        }
        p2.next=p2.next.next;
        return head;
    }
    public static void main(String[] args) {
       MyLinkedList myLinkedList=new MyLinkedList();
       myLinkedList.addNode(1);
       myLinkedList.addNode(4);
       myLinkedList.addNode(5);
        myLinkedList.head= removeNthFromEnd(myLinkedList.head,3);
       myLinkedList.printList();
    }
}
